/**
 *
 * Created by Pan,hongxue, 9/19/2011 6:46:17 PM
 * Copied from qiyi.com on 12/28/2011 6:15:37 PM
 *
 */

/* http://yule.iqiyi.com/20111227/df9cfdc80292e04d.html */
function  validateVideoUrl(ori_url) 
{
	var html = download_page(ori_url);
	var matches = html.match(/videoId : "(.*?)"/);
	if (!matches) {
		// Not Found
	  	return 'NotFoundVideo';
	}
	var dst_url = 'http://cache.video.qiyi.com/v/' + matches[1];
	var xml_str = download_page(dst_url);
	
	var fileList = [];
	var match, re = /<file>(http(.*?))<\/file>/g;
	while ((match = re.exec(xml_str)) != null) {
		var s_url = match[1];
		var key_json_str = download_page('http://data.video.qiyi.com/t.hml?tn=' + Math.random());
		var key_json = eval('(' + key_json_str + ')');
		var flv_json_str = download_page(s_url + '?v=' + get_key(key_json.t));
		var flv_json = eval('(' + flv_json_str + ')');
		fileList.push(flv_json.l);
	}
	if(fileList.length>0){
	    var duration = parse_xml(xml_str, 'video', 'fileDuration', 'duration');
		//matches = html.match(/<title>(.*?)<\/title>/);
		matches = html.match(/<title>([\s\S]*?)<\/title>/);
	    if(matches){
	 	   return 'success_title:' + encodeURIComponent(matches[1])
	 	          + '\n video_urls:' + encodeURIComponent(fileList)
	 	          + '\n seconds:' + Math.round(parseInt(duration)/1000);
	    }
	}
    return 'error:empty_path';
}

function js_get_media_url(ori_url) 
{
	var html = download_page(ori_url);
	var matches = html.match(/videoId : "(.*?)"/);
	if (!matches) {
		// Not Found
		return '';
	}

	var dst_url = 'http://cache.video.qiyi.com/v/' + matches[1];
	var xml_str = download_page(dst_url);
	var fileList = [];
	var match, re = /<file>(http(.*?))<\/file>/g;
	while ((match = re.exec(xml_str)) != null) {
		var s_url = match[1];
		var key_json_str = download_page('http://data.video.qiyi.com/t.hml?tn=' + Math.random());
		var key_json = eval('(' + key_json_str + ')');
		var flv_json_str = download_page(s_url + '?v=' + get_key(key_json.t));
		var flv_json = eval('(' + flv_json_str + ')');
		fileList.push(flv_json.l);
	}
	return fileList;
}

function get_key(t) {
	return (t ^ -1775748160) + Math.pow(2, 32);
}